package com.eques.doorbell.f5bff96034f0d5d8;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import org.json.JSONObject;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.List;
import java.util.concurrent.Executors;




public class HandleReceiver extends BroadcastReceiver {

	//根据不同厂商，需要修改的参数 {
	private static final String TAG = "tp_eques";

	private static final String KEY_ID = "f5bff96034f0d5d8";

	private static final String EQUES_APPKEY = "jhttPrj2KPeC2fSjaNBtkyh7QJJadxDm";

//	private static final String KEY_ID = "5d91e3b2b7fbb31c";
//
//	private static final String EQUES_APPKEY = "sdk_demo";
	//根据不同厂商，需要修改的参数 }

	/**
	 * 推送消息的action
	 */
	public static final String ACTION_EQUES_PUSH_MESSAGE = "com.eques.action.PUSH_MESSAGE" + "." + KEY_ID;

	/**
	 * 系统启动的action，通知第三方应用启动service
	 */
	public static final String ACTION_EQUES_BOOT_COMPLETED = "com.eques.action.BOOT_COMPLETED" + "." + KEY_ID;

	/**
	 * 系统ping的action，保持心跳使用，可以不使用
	 */
	public static final String ACTION_EQUES_PING = "com.eques.action.PING" + "." + KEY_ID;

	/**
	 * 第三方应用发送的验证信息
	 */
	public static final String ACTION_EQUES_ACCOUNT_VALIDATION = "com.eques.action.ACCOUNT_VALIDATION";

	/**
	 * 登录成功后发送设备信息及绑定的用户信息给第三方应用
	 */
	public static final String ACTION_EQUES_LOGIN_INFO = "com.eques.action.LOGIN_INFO" + "." + KEY_ID;

	/**
	 * 消息方法名，用于区分是那种消息类型
	 */
	public static final String EXTRA_METHOD = "method";

	/**
	 * 设备ID
	 */
	public static final String EXTRA_DEVID = "devid";

	/**
	 * 是否已经上传完成。
	 *	1. 上传成功
	 *	2. 未上传
	 */
	public static final String EXTRA_UPLOAD = "upload";

	/**
	 * 消息的内容类型
	 *	1. 文本
	 *  2. 图片
	 *  3. 视频
	 *  4.  Zip压缩包
	 *  5. 音频
	 */
	public static final String EXTRA_TYPE = "type";

	/**
	 * 上传文件的ID
	 *	门铃消息使用，其他消息不使用。
	 */
	public static final String EXTRA_FID = "fid";

	/**
	 * 与设备建立绑定关系的用户的用户名
	 */
	public static final String EXTRA_USERNAME = "username";

	/**
	 * 设备在移康云端服务器上的唯一标识
	 */
	public static final String EXTRA_DEVBID = "devbid";

	public static final String EXTRA_KEY_ID = "key_id";

	public static final String EXTRA_EQUES_APPKEY = "eques_appkey";

	public static final String EXTRA_JPUSH_APPKEY = "jpush_appkey";

	public static final String EXTRA_JPUSH_MASTER_SECRET = "jpush_master_secret";

	public static final String EXTRA_JPUSH_APPKEY_BUS = "jpush_appkey_bus";

	public static final String EXTRA_JPUSH_MASTER_SECRET_BUS = "jpush_master_secret_bus";


	@Override
	public void onReceive(Context context, Intent intent) {
		String action = intent.getAction();
		Log.d(TAG, "action: " + action);

		//注意，正式版本不要启动Activity，否则将影响可视门铃的正常使用！！！
		if (ACTION_EQUES_PUSH_MESSAGE.equals(action)) {
			//根据不同的消息类型，获取不同的参数
			int method = intent.getIntExtra(EXTRA_METHOD, 0);
			String devid = intent.getStringExtra(EXTRA_DEVID);
			int upload = intent.getIntExtra(EXTRA_UPLOAD, 0);
			int type = intent.getIntExtra(EXTRA_TYPE, 0);
			String fid = intent.getStringExtra(EXTRA_FID);

			Log.d(TAG, "method: " + method + "\t devid: " + devid + "\t upload: " + upload +
					"\t type: " + type + "\t fid: " + fid);

			Executors.newSingleThreadExecutor().execute(new UdpSender(method, devid));

		} else if (ACTION_EQUES_BOOT_COMPLETED.equals(action)) {
			//在监听到该广播后，需要将专属的APPKEY发送给可视门铃端，只有获取到正确的APPKEY后，可视门铃才可以正常的登录。
			Log.d(TAG, "set eques appkey: " + EQUES_APPKEY);

			Intent in = new Intent(ACTION_EQUES_ACCOUNT_VALIDATION);
			//传入key_id作为验证，要和厂商所使用的二维码中的key_id对应
			in.putExtra(EXTRA_KEY_ID, KEY_ID);
			in.putExtra(EXTRA_EQUES_APPKEY, EQUES_APPKEY);

			context.sendBroadcast(in);

		} else if (ACTION_EQUES_PING.equals(action)) {

		} else if (ACTION_EQUES_LOGIN_INFO.equals(action)) {
			String userName = intent.getStringExtra(EXTRA_USERNAME);
			String bid = intent.getStringExtra(EXTRA_DEVBID);
			Log.d(TAG, "userName: " + userName + "\t bid: " + bid);
		} else {
			Log.d(TAG, "error action");
		}
	}


	class UdpSender implements Runnable {

		private int method;
		private String bid;

		private static final String broadcast_addr = "255.255.255.255";
		private static final int port = 20006;

		public UdpSender(int method, String bid){
			this.method = method;
			this.bid = bid;
		}

		@Override
		public void run(){
			try {
				JSONObject jsonmsg = new JSONObject();
				jsonmsg.put("from", bid);
				jsonmsg.put("method", getMethodStr(method));
				byte[] sendmsg = ("t11" + jsonmsg.toString()).getBytes();
				DatagramSocket udpSocket = new DatagramSocket();
				DatagramPacket dataPacket = new DatagramPacket(sendmsg, sendmsg.length, getBroadcastIpAddress(),port);
				udpSocket.send(dataPacket);
				udpSocket.close();
				Log.i(TAG, "message:" + new String(sendmsg));
			} catch(Exception e){
				e.printStackTrace();
				Log.e(TAG, e.getMessage());
			}
		}
	}


	private String getMethodStr(int type){
		String methodName = "";
		switch(type){
			case 1://报警
				methodName = "alarm";
				break;
			case 2://呼叫
				methodName = "call";
				break;
			case 3://门锁开锁信息
				methodName = "lockopen";
				break;
			case 4://门锁告警信息
				methodName = "lockalarm";
				break;
			case 5://消息
				methodName = "message";
				break;
			case 6://其他
				methodName = "other";
				break;
		}
		return methodName;
	}

 public static InetAddress getBroadcastIpAddress()
    {
        try {
            for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();)
            {
                NetworkInterface intf = (NetworkInterface) en.nextElement();
                List<InterfaceAddress> faces = intf.getInterfaceAddresses();
                for (InterfaceAddress ifa : faces){
                    InetAddress ia = ifa.getAddress();
                    if (!ia.isLoopbackAddress() && !ia.isLinkLocalAddress()){
                        return ifa.getBroadcast();
                    }
                }
            }
        } catch (SocketException ex)
        {
            Log.e("IpAddress", ex.toString());
        }
        return null;
    }
}
